package cn.edu.scau.cmi.hekaimin.Hibernate.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.hekaimin.Hibernate.domain.Teacher;
import cn.edu.scau.cmi.hekaimin.Hibernate.util.HibernateUtils;

public class TeacherDao implements BaseDao<Teacher>{
	
	 
	@Override
	public void add(Teacher t) {
		if(t != null) {
		  Session session = HibernateUtils.getSession();	
		  session.save(t);
		  HibernateUtils.colseSession(session);
		}	
	}

	@Override
	public void update(Teacher t) {
		
		if( t != null) {
			Session session = HibernateUtils.getSession();
			session.update(session.merge(t));
			HibernateUtils.colseSession(session);
		}
	}

	@Override
	public void delete(int id) {
		Session session = HibernateUtils.getSession();
		String hql = "delete from Teacher where t_id = " + id;
		session.createQuery(hql).executeUpdate();
		HibernateUtils.colseSession(session);
	}

	@Override
	public List<Teacher> getAll() {
		Session session = HibernateUtils.getSession();
		
		String hql = "from Teacher";
		List<Teacher> list = session.createQuery(hql).list();
	//	HibernateUtils.colseSession(session);
		return list;
	}
	@Override
	public Teacher findById(int id) {
		
		Session session = HibernateUtils.getSession();
		String hql = "from Teacher where t_id = " + id;
		Teacher tea = (Teacher) session.createQuery(hql).uniqueResult();
		HibernateUtils.colseSession(session);
		return tea;
	}

	@Override
	public List<Teacher> findByExample(Teacher t) {
		Session session = HibernateUtils.getSession();
		try {
			List<Teacher> results = session.createCriteria("cn.edu.scau.cmi.hekaimin.Hibernate.domain.Teacher").add(Example.create(t)).list();
			HibernateUtils.colseSession(session);
			return results;
		}catch(RuntimeException re) {
			throw re;
		}
		
	}

	@Override
	public List<Teacher> findByProperty(String propertyName, Object value) {
		Session session = HibernateUtils.getSession();
		try {
			String queryString  =  "from Teacher as model where model." + propertyName + "=?";
			Query queryObject = session.createQuery(queryString);
			queryObject.setParameter(0, value);
			List<Teacher> list = queryObject.list();
			HibernateUtils.colseSession(session);
			return list;
		}catch(RuntimeException re) {
			throw re;
		}
		
	}

	@Override
	public List<Teacher> findByName(Object name) {
		
		return findByProperty("t_name",name);
	}

}
